package com.blork.sowidget;

import static android.provider.BaseColumns._ID;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

public class SoService extends Service implements Runnable{

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	public void onCreate() {
		Log.d("sowidget", "Service created."); 
		startService();      
	}
	
	private void startService(){
		Log.d("sowidget", "Service started.");
		Thread thread = new Thread(this);
		thread.start();
	}
	
	public void run(){
		Log.d("sowidget", "Service thread running.");
		try{
			
			URL url = new URL("http://api.stackoverflow.com/0.8/questions?sort=hot&key=");
	        
			Log.d("sowidget", "Parsing JSON...");
	        JSONObject json = (JSONObject) new JSONTokener(getJSON(url)).nextValue();
	        JSONArray questions = json.getJSONArray("questions");

	        saveQuestions(questions, 10);
	                   
        }catch(MalformedURLException e){
        	Log.e("sowidget",e.toString());	        	
        }catch(IOException e){
        	Log.e("sowidget",e.toString());	
        } catch (JSONException e) {
        	Log.e("sowidget",e.toString());
		}
		
        
        QuestionData qs = new QuestionData(this);
	    SQLiteDatabase db = qs.getReadableDatabase();
		Cursor questionCursor = db.query("questions", new String[] {_ID, "q_id, title, tags, votes, answer_count, user_name"}, 
	                null, null, null, null, null);
		
        
        questionCursor.moveToFirst(); 
        
        RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.widget);
        
        ComponentName thisWidget = new ComponentName( this, Widget.class );
        
        views.setViewVisibility(R.id.content, View.VISIBLE);
        views.setViewVisibility(R.id.loading, View.GONE);
        
        views.setTextViewText(R.id.title, questionCursor.getString(questionCursor.getColumnIndex("title")));
        views.setTextViewText(R.id.votes, questionCursor.getString(questionCursor.getColumnIndex("votes")));
        views.setTextViewText(R.id.answers, questionCursor.getString(questionCursor.getColumnIndex("answer_count")));
       
        String[] tag = questionCursor.getString(questionCursor.getColumnIndex("tags")).split(",");
        views.setTextViewText(R.id.tags, tag[0]); 
        
        Intent intent = new Intent(this, QuestionList.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.content, pendingIntent);
        
        AppWidgetManager.getInstance(this).updateAppWidget(thisWidget, views); 
        
        questionCursor.close();
        stopSelf();
        
	}
	
    private void saveQuestions(JSONArray questions, int num){
    	Log.d("sowidget", "Saving questions to DB...");
    	
    	QuestionData qData = new QuestionData(this);
    	
		SQLiteDatabase db = qData.getWritableDatabase();
		
		db.delete("questions", null, null);
		
		for(int x = 0; x <= num; x++){ 
			Log.d("sowidget", "Saving question...");
			try {
				JSONObject question = questions.getJSONObject(x);
				
				ContentValues values= new ContentValues();
				Log.d("sowidget", "Question ID: "+question.getString("question_id"));
				
				values.put("q_id", question.getString("question_id"));
				values.put("title", question.getString("title"));
				
				JSONArray tags = question.getJSONArray("tags");
				
				String niceTags = "";
				
				for(int i = 0; i < tags.length(); i++){
					if(i != 0){
						niceTags += ", ";
					}
					niceTags += tags.getString(i);
				}
				
				values.put("tags", niceTags);
				
							
				int votes = question.getInt("up_vote_count") - question.getInt("down_vote_count");
				values.put("votes", votes+" votes");
				
				values.put("answer_count", question.getInt("answer_count")+" answers");
				
				JSONObject owner = question.getJSONObject("owner");
				String userName = "Asked by "+owner.getString("display_name");
				values.put("user_name", userName);
				
				db.insertOrThrow("questions", null, values);
				
			} catch (JSONException e) {
				Log.e("sowidget", e.toString());
			}
		}
		
		db.close();
    }
    
    private static String getJSON(URL url) throws IOException {
        final URLConnection connection = url.openConnection();
        connection.connect();
        InputStream stream;
        
        Log.d("sowidget", "Getting questions...");
        
        if (connection.getContentEncoding().equals("gzip")) {
        		Log.d("sowidget", "File is compressed.");
        		stream = new GZIPInputStream(connection.getInputStream());
        } else {
        		stream = connection.getInputStream();
        }
        String ct = connection.getContentType();
        final BufferedReader reader;
        if (ct.indexOf("charset=") != -1) {
        		ct = ct.substring(ct.indexOf("charset=") + 8);
                reader = new BufferedReader(new InputStreamReader(stream, ct));
        }else {
        		ct = null;
                reader = new BufferedReader(new InputStreamReader(stream));
        }
        final StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
        	sb.append(line + '\n');
            line = reader.readLine();
        }
        return sb.toString();
    }
}
  